import React, { Component, Suspense } from "react";
import PageHeaderWrapper from "@/components/PageHeaderWrapper";
import { connect } from "dva";
import PageLoading from "@/components/PageLoading";
import GridContent from "@/components/PageHeaderWrapper/GridContent";
import { FormattedMessage } from "umi-plugin-react/locale";
import Ellipsis from "@/components/Ellipsis";
import {
	Row, Col, Card, Button, Table, Pagination, Modal, message,
	Input, Icon, List, Avatar, Tabs
} from "antd";
import styles from "./index.less";
import tableDataCheck from "@/utils/isBackPrevPage";
import UserSession from "@/UserSession";
import { routerRedux } from "dva/router";

const { TabPane } = Tabs;
const confirm = Modal.confirm;
const ApiServiceCondition = React.lazy(() => import("./apiServiceCondition"));
@connect(({ customApi, loading }) => ({
	customApi,
	loading: loading.effects["customApi/fetch"],
}))
class CustomApi extends Component {
	constructor(props) {
		super(props);
		this.state = {
			page: 1,
			limit: 15,
			currentApiId: null,
			apiNames: null,
			loading: true,
			list: [],
			total: 0,
			apiServiceConditionShow: false,
			apiTitle: "",
			apiId: "",
			apiLoading: false,
			activeKey: "1",
		};
	}

	componentDidMount() {
		this.fetchApiListById();
	}

	fetchApiListById = () => {
		const that = this;

		const { activeKey, page, apiNames } = that.state;
		const { dispatch, currentUser } = this.props;

		let urlPrefix = "";

		if (activeKey == 2) {
			urlPrefix = "headquarters";
		}

		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "customApi/fetch",
				payload: {
					current: page,
					size: activeKey == 2 ? 16 : 15,
					search: apiNames,
					// urlPrefix,
					type: activeKey,
				},
				callback: (res) => {
					this.setState({
						loading: false,
						list: res.records ? res.records : [],
						total: activeKey == 2 ? parseInt(res.total) : parseInt(res.total) + 1,
					});
				},
			});
		});
	};

	delApiById(id) {
		const that = this;
		const { dispatch } = that.props;
		that.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "customApi/delete",
				payload: { id: id },
				callback: (res) => {
					message.info(res.message);
					//判断是否需要加载上一页数据 2022.4.8
					const { list, page } = that.state;
					const newCurrent = tableDataCheck(list, page);
					that.setState({ page: newCurrent, }, () => {
						that.fetchApiListById();
					});
				},
			});
		});
	}

	editApi(id) {
		const { dispatch } = this.props;
		const { activeKey } = this.state;
		let urlPrefix = "";
		if (UserSession.isAdmin()) {
			urlPrefix = "headquarters";
		} else {
			if (activeKey == 2) {
				urlPrefix = "headquarters";
			}
		};
		let url = `/knowledgeDesign/customApi/edit/${id}/${urlPrefix}`;

		this.reqRef = requestAnimationFrame(() => {
			dispatch(
				routerRedux.push({
					pathname: url,
				})
			);
		});
	}

	delApi(id, name) {
		const that = this;
		confirm({
			title: `删除【${name}】任务`,
			content: "确认删除该API接口吗？",
			okText: "确认",
			okType: "primary",
			cancelText: "取消",
			onOk() {
				that.delApiById(id);
			},
			onCancel() { },
		});
	}

	setApiName(val) {
		this.setState({ apiNames: val, loading: true, }, () => {
			this.fetchApiListById();
		});
	}

	addApi() {
		const { dispatch } = this.props;
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "customApi/redirect",
				payload: {},
			});
		});
	}

	// 翻页
	fanye(e) {
		this.setState({ page: e, loading: true, }, () => {
			this.fetchApiListById();
		});
	}

	showApiServiceConditionShow = (apiId, name) => {
		this.setState({
			apiServiceConditionShow: true,
			apiLoading: true,
			apiTitle: name,
			apiId,
		});
	};

	hideApiServiceConditionShow = () => {
		this.setState({
			apiServiceConditionShow: false,
			apiId: "",
		});
	};

	render() {
		const { list, loading, total, limit, apiServiceConditionShow, apiTitle, apiId, apiLoading, activeKey } = this.state;

		return (
			<GridContent>
				<Suspense fallback={<PageLoading />}>
					<PageHeaderWrapper>
						<Card className={styles.cardList}>
              <List
                rowKey='id'
                loading={loading}
                pagination={{
                  onChange: (page) => {
                    this.fanye(page);
                  },
                  pageSize: 16,
                  total,
                  showQuickJumper: true,
                }}
                grid={{ gutter: 24, lg: 4, md: 4, sm: 2, xs: 1 }}
                dataSource={["", ...list]}
                renderItem={(item) =>
                  item ? (
                    <List.Item key={item.id}>
                      <Card
                        hoverable
                        className={styles.card}
                        actions={[
                          <a onClick={() => this.delApi(item.id, item.name)}>删除</a>,
                          <a onClick={() => this.editApi(item.id)}>编辑</a>,
                        ]}
                      >
                        <Card.Meta
                          avatar={
                            <Avatar className={styles.cardAvatar}>
                              {item.name.substr(0, 1)}{" "}
                            </Avatar>
                          }
                          title={
                            <a
                              title={item.name}
                              style={{
                                width: "100%",
                                display: "block",
                                overflow: "hidden",
                                whiteSpace: "nowrap",
                                textOverflow: "ellipsis",
                              }}
                            >
                              {item.name}
                            </a>
                          }
                          description={
                            <Ellipsis className={styles.item} lines={3}>
                              {item.isUsed ? (
                                <span
                                  style={{ color: "rgb(9, 178, 255)" }}
                                  onClick={() =>
                                    this.showApiServiceConditionShow(item.id, item.name)
                                  }
                                >
                                  <Icon type='play-circle' className={styles.icon} />
                                  使用中
                                </span>
                              ) : (
                                ""
                              )}
                            </Ellipsis>
                          }
                        />
                      </Card>
                    </List.Item>
                  ) : (
                    <List.Item>
                      <Button
                        type='dashed'
                        htmlType='button'
                        className={styles.newButton}
                        onClick={() => this.addApi()}
                      >
                        <Icon type='plus' /> 添加接口
                      </Button>
                    </List.Item>
                  )
                }
              />
							<ApiServiceCondition
								visible={apiServiceConditionShow}
								title={apiTitle}
								onClosed={() => this.hideApiServiceConditionShow()}
								id={apiId}
								loading={apiLoading}
							/>
						</Card>
					</PageHeaderWrapper>
				</Suspense>
			</GridContent>
		);
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(CustomApi);
